# -*- coding: utf-8 -*-
# @Author : Orange
# @File : algorithm.py
from phecda.exception import AlgException

from 排气温度.data_processing import *
import datetime
import numpy as np
import pickle
from 排气温度.get_data import get_iv_data
from matplotlib import pyplot as plt


def call(*args, **kwargs):
    param = kwargs.get('param')
    # model = kwargs.get('model')

    try:
        data = get_iv_data(start_time=param['start_time'], end_time=param['end_time'], equip_id=param['equip_id'],
                           station_id=param['station_id'], equip_mk=param['equip_mk'])
        data_1, data_p0 = data_processing(data)
        x = data_1.loc[:, ['TchwOut', 'TchwIn', 'TcwOut', 'IratioCpr', 'Pelec', 'TcwIn']]
        y = data_1['TcprAirOut']
        with open(r'C:\Users\chengjingd\PycharmProjects\pythonProject\.XGBModel.pkl', 'rb') as f:
            model = pickle.load(f)
        y_hat = model.predict(np.array(x))
        # 对于Pelec=0的排气温度，无需预测，只要采用原来的即可。
        y_1 = pd.concat([y, data_p0], axis=0).sort_index()
        y_hat = pd.Series(y_hat, index=y.index)
        y_hat_1 = pd.concat([y_hat, data_p0], axis=0).sort_index()
        result = {
            "y_pred": y_hat_1.tolist(), "y_real": y_1.tolist()
        }

        return result, param
    except:
        result = None
        raise AlgException("暂不支持该故障分析", code=550)

    finally:
        return result, param


params = {"param":
    {
        "domain": "EMS",
        "equip_id": "ECR01",
        "equip_mk": "ECR",
        "station_id": "PARK569_EMS01",
        "start_time": "2021-06-15 14:00:00",
        "end_time": "2021-06-16 14:00:00"
    }
}
result, param = call(**params)

# # """可视化"""
# plt.figure()
# t = len(y_1)
# print(t)
# plt.plot(np.arange(t), y_hat_1, 'c*-')
# plt.plot(np.arange(t), y_1, 'm.-.')
# plt.legend(['y_real', 'y_pred'])
# # 标记异常点
# print(y_1)
# print(y_hat_1)
# y_diff = y_1 - y_hat_1
# for idx, val in enumerate(y_diff):
#     if (val > 1):
#         print("预测值：%s，真实值：%s"%(y_hat_1[idx],y_1[idx]))
#         plt.scatter(idx, y_hat_1[idx], c='red', edgecolors='black')
#         plt.annotate(r"$this\ is\ a\ Outlier,bias=$" + str('%.2f' % val), xy=(idx, y_hat_1[idx]), xycoords='data',xytext=(+30, -30),
#                     textcoords='offset points', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
# plt.show()
